package com.wmh.baseservice.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.UUIDUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.*;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.UsRentOrder;
import com.wmh.baseservice.user.service.UsInfoService;
import com.wmh.baseservice.user.service.UsRentOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@Api(tags = "用户端-租赁相关接口")
@RestController
@RequestMapping(value = "user/rent", produces = "text/plain;charset=utf-8")
public class UsRentController {


    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private MerchantPlotRentalMenuService merchantPlotRentalMenuService;
    @Resource
    private UsRentOrderService usRentOrderService;
    @Resource
    private MerchantVegetablePlotService merchantVegetablePlotService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantPlotRentService merchantPlotRentService;

    @ApiOperation("提交租赁订单")
    @PostMapping("subOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "区域id", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "rentMenuId", value = "套餐id", required = true),
    })
    @ParameterVerify(notNull = {"id", "rentMenuId"})
    public String subOrder(Long id, Long rentMenuId) {
        Long usId = (Long) request.getAttribute("usId");
        MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantPlotRegion)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        int count=usRentOrderService.queryShortOrder(usId);
        if (count>=1){
            return ReturnBody.error("您已提交过订单，请稍后再试");
        }
        if (merchantPlotRegion.getStatus() == 2) {
            UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
            if (!merchantPlotRegion.getMerchantId().equals(usInfo.getMerchantId())) {
                return ReturnBody.error("该区域已出租");
            }
        }
        MerchantPlotRentalMenu merchantPlotRentalMenu = merchantPlotRentalMenuService.getByIdForUpdate(rentMenuId);
        if (!CommUtil.checkNull(merchantPlotRentalMenu)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (!CommUtil.checkNull(usInfo.getName(), usInfo.getPhone())) {
            return ReturnBody.error("请先到个人中心完善个人手机号和姓名");
        }
        //不可租自己的土地
        if (CommUtil.checkNull(usInfo.getMerchantId())) {
            if (usInfo.getMerchantId().equals(merchantPlotRegion.getMerchantId()) && merchantPlotRegion.getStatus() < 2) {
                return ReturnBody.error("不可租自己添加的区域");
            } else {
                MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usInfo.getMerchantId());
                //不可租主商家添加的土地
                if (merchantInfo.getParentId().equals(merchantPlotRegion.getMerchantId())) {
                    return ReturnBody.error("不可租合伙人添加的区域");
                }
            }
        }
        //查询土地押金,没填或者为0时不可租赁
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getByIdForUpdate(merchantPlotRegion.getPlotId());
        if (!CommUtil.checkNull(merchantVegetablePlot, merchantVegetablePlot.getDeposit())
                || merchantVegetablePlot.getDeposit().compareTo(BigDecimal.ZERO) <= 0) {
            return ReturnBody.error("很抱歉，因为商家未设置土地押金，暂时无法提供租赁服务");
        }
        JSONObject object = new JSONObject(true);
        object.put("describe", merchantPlotRentalMenu.getDescribe());
        object.put("day", merchantPlotRentalMenu.getDay());
        object.put("merchantId", merchantPlotRentalMenu.getMerchantId());
        UsRentOrder usRentOrder = new UsRentOrder();
        //如果当前是续租，那么不需要缴纳押金，正常租赁则需要缴纳押金
        BigDecimal payAmount = BigDecimal.ZERO;
        if (CommUtil.checkNull(usInfo.getMerchantId())) {
            MerchantPlotRegion region = merchantPlotRegionService.getOneForUpdate(new QueryWrapper<MerchantPlotRegion>()
                    .eq(MerchantPlotRegion.MERCHANT_ID, usInfo.getMerchantId())
                    .eq(MerchantPlotRegion.ID, id).eq(MerchantPlotRegion.STATUS, 2));
            if (CommUtil.checkNull(region)) {
                //还在租赁期间，续租操作
                payAmount = merchantPlotRentalMenu.getPrice();
                usRentOrder.setType(2);
            } else {
                //正常租
                payAmount = payAmount.add(merchantVegetablePlot.getDeposit());
                payAmount = payAmount.add(merchantPlotRentalMenu.getPrice());
                object.put("deposit", merchantVegetablePlot.getDeposit());
                usRentOrder.setType(1);
            }
        } else {
            //无商家信息，普通用户第一次正常租
            payAmount = payAmount.add(merchantVegetablePlot.getDeposit());
            payAmount = payAmount.add(merchantPlotRentalMenu.getPrice());
            object.put("deposit", merchantVegetablePlot.getDeposit());
            usRentOrder.setType(1);
        }
        usRentOrder.setOrderNum(UUIDUtil.getTimeId() + UUIDUtil.getLetter()).setPayAmount(payAmount)
                .setRegionId(id).setRentMenuId(rentMenuId).setUsId(usId).setSnapshot(object.toJSONString());
        if (!usRentOrderService.save(usRentOrder)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success(usRentOrder.getOrderNum());
    }

    @ApiOperation("租赁订单列表")
    @PostMapping("orderList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "status", value = "0待付款 1已付款 -1已取消", required = false),
    })
    public String orderList(PageInfo pageInfo, Integer status) {
        Long usId = (Long) request.getAttribute("usId");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsRentOrder> pageResult = new PageUtil<UsRentOrder>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(status)) {
                queryWrapper.eq(UsRentOrder.STATUS, status);
            }
            queryWrapper.eq(UsRentOrder.US_ID, usId);
            usRentOrderService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(item.getRegionId());
            item.setRegionName(merchantPlotRegion.getName());
            MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getByIdForUpdate(merchantPlotRegion.getPlotId());
            item.setPlotName(merchantVegetablePlot.getPlotName());
            item.setLat(merchantVegetablePlot.getLat());
            item.setLng(merchantVegetablePlot.getLng());
            item.setLon(merchantPlotRegion.getLon());
            item.setWide(merchantPlotRegion.getWide());
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("余额支付")
    @PostMapping("payAmount")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "订单编号", required = true),
    })
    public String payAmount(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsRentOrder usRentOrder = usRentOrderService.getOneForUpdate(new QueryWrapper<UsRentOrder>().eq(UsRentOrder.ORDER_NUM, orderNum));
        if (!CommUtil.checkNull(usRentOrder) || !usRentOrder.getUsId().equals(usId)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (usRentOrder.getStatus() != 0) {
            return ReturnBody.error("订单状态错误");
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (usInfo.getBalance().compareTo(usRentOrder.getPayAmount()) < 0) {
            return ReturnBody.error("用户余额不足");
        }
        usInfo.setBalance(usInfo.getBalance().subtract(usRentOrder.getPayAmount()));
        MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(usRentOrder.getRegionId());
        if (!CommUtil.checkNull(merchantPlotRegion)) {
            return ReturnBody.error("区域不存在");
        }
        //判断是否租出
        if (CommUtil.checkNull(usInfo.getMerchantId())) {
            //商家续租
            if (merchantPlotRegion.getStatus() == 2 && !merchantPlotRegion.getMerchantId().equals(usInfo.getMerchantId())) {
                return ReturnBody.error("该区域被租出");
            }
        } else {
            if (merchantPlotRegion.getStatus() == 2) {
                return ReturnBody.error("该区域被租出");
            }
        }
        usRentOrder.setStatus(1);
        merchantPlotRegionService.payAmount(usRentOrder, merchantPlotRegion, usInfo);
        return ReturnBody.success();
    }

    @ApiOperation("取消订单")
    @PostMapping("cancelOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "orderNum")
    public String cancelOrder(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsRentOrder usRentOrder = usRentOrderService.getOneForUpdate(new QueryWrapper<UsRentOrder>().eq(UsRentOrder.ORDER_NUM, orderNum).eq(UsRentOrder.US_ID, usId));
        if (!CommUtil.checkNull(usRentOrder) || !usRentOrder.getUsId().equals(usId)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (usRentOrder.getStatus() != 0) {
            return ReturnBody.error("订单状态错误");
        }
        usRentOrder.setStatus(-1);
        if (!usRentOrderService.updateById(usRentOrder)) {
            throw new ServiceException();
        }
        return ReturnBody.success();
    }

    @ApiOperation("租赁套餐详情")
    @PostMapping("rentalMenuDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String rentalMenuDetail(Long id) {
        MerchantPlotRentalMenu result = merchantPlotRentalMenuService.getByIdForUpdate(id);
        if (result == null) {
            return ReturnBody.error("套餐信息丢失");
        }
        return ReturnBody.success(result);
    }
}
